package com.youlai.boot.form.validator;

import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.validation.Constraint;
import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;
import jakarta.validation.Payload;

import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;

import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

/**
 * JSON格式校验注解
 */
@Target({ FIELD })
@Retention(RUNTIME)
@Constraint(validatedBy = JsonFormatValidator.class)
@Documented
public @interface ValidJson {
    String message() default "Invalid JSON format";
    Class<?>[] groups() default {};
    Class<? extends Payload>[] payload() default {};

}

/**
 * JSON格式校验器
 */
class JsonFormatValidator implements ConstraintValidator<ValidJson, String> {
    private static final ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public boolean isValid(String s, ConstraintValidatorContext constraintValidatorContext) {
        if (s == null || s.trim().isEmpty()) {
            return true; // 空值校验由@NotBlank处理
        }
        try {
            objectMapper.readTree(s);
            return true;
        } catch (Exception e) {
            return false;
        }
    }
}
